package thread.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 1.必须使用volatile
 * 2.不能是static final
 *
 * @author liweimin
 * @date 2021/4/29 17:04
 * @since
 */
public class AtomicIntegerFiledUpdateTest {

    public static void main(String[] args) {
        AtomicUser user = new AtomicUser(1, 13);
        for (int i = 0; i < 10; i++) {
            new SubThread(user).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(user);
    }

    static class SubThread extends Thread {
        private AtomicUser atomicUser;

        private AtomicIntegerFieldUpdater<AtomicUser> updater = AtomicIntegerFieldUpdater.newUpdater(AtomicUser.class, "age");

        public SubThread(AtomicUser user) {
            this.atomicUser = user;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println(updater.getAndIncrement(atomicUser));
            }
        }
    }
}
